package cn.tedu.web.lsw.servlet;

import cn.tedu.web.lsw.JdbcUtils;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;


public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取请求中键名为 u 的值
        String username = req.getParameter("u");
        // 获取请求中键名为 p 的值
        String password = req.getParameter("p");
        // 获取请求中键名为 c 的值
        String code = req.getParameter("c");
        System.out.println(username);
        System.out.println(password);
        System.out.println(code);

        // 从请求中获取 Session
        HttpSession session = req.getSession();
        // 从 Session 中获取名为 C 的数据的值
        Object c = session.getAttribute("c");
        boolean isTrue = code != null && code.equals(c);
        if (!isTrue) {
            PrintWriter writer = resp.getWriter();
            writer.write("code is error");
            writer.flush();
            writer.close();
            return;
        }

        String sql = "SELECT id FROM `user` WHERE username = ? AND `password` = MD5(?)";
        Long id = JdbcUtils.select(sql, Long.class, username, password);
        if (id != null) {
            // 在登录成功之后，将用户的 ID 保存到 session 中
            session.setAttribute("UID", id);
            // 登录成功，去首页 http://localhost:8080/wyl/index.jsp
            resp.sendRedirect("/lsw/");
        } else {
            // 登录失败，去登录页
            resp.sendRedirect("/lsw/login.jsp");
        }
    }
}